package com.interactiveyang.meet;

import oauth.signpost.OAuth;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;

public class OAuthStageTwo extends AsyncTask<Uri, Void, Void> {

	private Context	context;
	private CommonsHttpOAuthProvider provider;
	private CommonsHttpOAuthConsumer consumer;

	public OAuthStageTwo(Context context, CommonsHttpOAuthProvider provider, CommonsHttpOAuthConsumer consumer) {
		this.context = context;
		this.provider = provider;
		this.consumer = consumer;
	}


	@Override
	protected Void doInBackground(Uri...params) {
		final Uri uri = params[0];
		final String TAG = getClass().getName();
		
		final SharedPreferences prefs = context.getSharedPreferences(C.OAuth.PREF_NAME, Context.MODE_PRIVATE);		
		final String oauth_verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
		
		Log.v("consumerkey", consumer.getConsumerKey());
		
		try {
			provider.retrieveAccessToken(consumer, oauth_verifier);

			final Editor edit = prefs.edit();
			edit.putString(OAuth.OAUTH_TOKEN, consumer.getToken());
			edit.putString(OAuth.OAUTH_TOKEN_SECRET, consumer.getTokenSecret());
			edit.commit();

			Log.i(TAG, "OAUTH STAGE TWO OK!");
			
		} catch (Exception e) {
			Log.e(TAG, "OAUTH STAGE TWO ERROR", e);
		}

		return null;
	}
}